﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;
using CatUtils.Utils.Enhance.ThreadTool;
using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.Media;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using static CatUtils.Utils.SpecialUtils.ContentRecognition.BaiduUtils.ImageRecognition.BaiduJson;

namespace CatUtils.Utils.SpecialUtils.ContentRecognition.BaiduUtils.ImageRecognition
{
    /// <summary>
    /// 图片鉴黄
    /// </summary>
    public class BaiduImgSexy
    {
        /// <summary>
        /// 单个文件返回模糊结果  正常0 性感1 色情2
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public int GetFile(string FileName)
        {
            JObject result = GetResult(FileName, true);
            if (result == null)
                return 0;

            return GetJsonMode(result);
        }

        /// <summary>
        ///  获取动漫图的权重值 如果是true 则需要删除
        /// </summary>
        /// <param name="FileLink"></param>
        /// <returns></returns>
        public bool GetComicLink(string FileLink)
        {
            string FilePath = WebHelper.DownloadToFile(FileLink, FileNameHelper.CreateTempFileName());
            bool Value = GetComicFile(FilePath);
            FileHelper.FileDelete(FilePath);
            return Value;
        }

        /// <summary>
        /// 获取动漫图的权重值 如果是true 则需要删除
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public bool GetComicFile(string FilePath)
        {
            if (FilePath == "")
                return false;
            JObject result = GetResult(FilePath, true);
            if (result == null)
                return false;
            try
            {
                BaiduJson.Root AllJson = JsonConvert.DeserializeObject<BaiduJson.Root>(result.ToString());
                if (AllJson.conclusion == "色情")
                {
                    PrintLog.ENoWrite("直接判定为违规图，删除！");
                    return true;
                }
                if (AllJson.result_fine != null)
                    foreach (var item in AllJson.result_fine)
                    {
                        bool BreakFlag = false;
                        foreach (var Fine in BaiduImgHelper.result_fine)
                        {
                            if (item.class_name == Fine.class_name && item.probability > Fine.probability)
                            {
                                PrintLog.ENoWrite($"{item.class_name }违规：{item.probability}");
                                BreakFlag = true;
                                break;
                            }
                        }
                        if (BreakFlag)
                            return true;
                    }
                else
                {
                    if (result.ToString().IndexOf("Open api qps request limit reached") >= 0)
                    {
                        PrintLog.ENoWrite("QPS速率过高，休眠十秒！");
                        ThreadSleep.SetSecondClock(10, true);
                        return GetComicFile(FilePath);
                    }
                    if (result.ToString().IndexOf("Open api daily request limit reached") >= 0)
                    {
                        BaiduImgHelper.SetMaxCount();
                        PrintLog.ENoWrite("已经超过每日最高限制，更新项目限制");
                    }
                    Console.WriteLine(result.ToString());
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                Console.WriteLine(result.ToString());
            }
            return false;
        }

        /// <summary>
        /// 获取返回值
        /// </summary>
        /// <param name="FilePath"></param>
        /// <param name="AddCount"></param>
        /// <returns></returns>
        private static JObject GetResult(string FilePath, bool AddCount)
        {
            try
            {
                if (BaiduImgHelper.GetJumpFlag(AddCount))
                {
                    return null;
                }

                var client = BaiduCurrencyHelper.GetImgClient(BaiduImgHelper.LocalAntiPorn, BaiduImgHelper.API_KEY_Path, BaiduImgHelper.SECRET_KEY_Path);
                if (FilePath == "" || client == null)
                    return null;
                FilePath = new ImageHelper().MakeThumbnail(FilePath, 600, 800, ImageFormat.Jpeg);
                var image = File.ReadAllBytes(FilePath);
                var result = client.Detect(image);
                FileHelper.FileDelete(FilePath);
                return result;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return null;
        }

        /// <summary>
        /// 获取JSON返回结果 粗略判断
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        private int GetJsonMode(JObject result)
        {
            try
            {
                BaiduJson.Root AllJson = JsonConvert.DeserializeObject<BaiduJson.Root>(result.ToString());

                switch (AllJson.conclusion)
                {
                    case "正常":
                        return 0;

                    case "性感":
                        return 1;

                    case "色情":
                        return 2;
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return -1;
        }
    }
}